package com.aw.baselib.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;

import com.aw.baselib.base.AwBaseApplication;

import java.util.Stack;


/**
 * @author : hzw
 * @date : 2020/6/19 10:45
 */
public class AwActivityUtil {

    public static boolean isTopActivity(Activity activity)
    {
        ActivityManager am = (ActivityManager)activity.getSystemService(activity.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        return cn.getClassName().contains(activity.getClass().getName());
    }

    public static boolean isTopActivity(String className) {
        ActivityManager am = (ActivityManager) AwBaseApplication.getInstance().getSystemService(AwBaseApplication.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        return cn.getClassName().equals(className);
    }

    private static Stack<Activity> stack;
    private static AwActivityUtil manager;

    /**
     * 获取实例
     */
    public static synchronized AwActivityUtil getInstance() {
        if (manager == null) {
            manager = new AwActivityUtil();
            stack = new Stack<>();
        }
        return manager;
    }

    /**
     * 添加Activity
     */
    public synchronized void addActivity(Activity activity) {
        stack.add(activity);
    }

    /**
     * 移除Activity
     */
    public synchronized void removeActivity(Activity activity) {
        stack.remove(activity);
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls) {
        for (Activity activity : stack) {
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
                return;
            }
        }
    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            activity.finish();
            stack.remove(activity);
        }
    }

    /**
     * 是否存在Activity
     */
    public boolean containsActivity(Class<?> cls) {
        for (Activity activity : stack) {
            if (activity.getClass().equals(cls)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        for (Activity activity : stack) {
            if (activity != null) {
                activity.finish();
            }
        }
        stack.clear();
    }
}
